package com.dxy.server;

import com.dxy.server.utils.PropertiesUtil;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * socket服务器
 */
public class MySocketServer {

    // 端口
    private int port;

    // 线程池
    private ExecutorService threadPool;

    // socket服务端
    private ServerSocket serverSocket;

    public MySocketServer(int port) {
        this.port = port;
        init();
    }

    // 初始化服务器
    private void init() {
        this.threadPool = new ThreadPoolExecutor(
                Integer.parseInt(PropertiesUtil.getProperty("thread-pool.core-pool-size")),
                Integer.parseInt(PropertiesUtil.getProperty("thread-pool.maximun-pool-size")),
                Long.parseLong(PropertiesUtil.getProperty("thread-pool.keep-alive-time")),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(Integer.parseInt(PropertiesUtil.getProperty("thread-pool.capacity"))),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    // 销毁服务器
    private void close() {
        System.out.println("销毁服务器");
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (threadPool != null) {
            threadPool.shutdownNow();
        }
    }

    // 启动服务器
    public void start() {
        new Thread() {
            @Override
            public void run() {
                try {
                    serverSocket = new ServerSocket(port);
                    System.out.println("服务器在" + port + "端口上已启动");
                    while (true) {
                        // 等待客户端连接到来
                        Socket socket = serverSocket.accept();
                        threadPool.execute(new MyServerThread(socket));
                        System.out.println("一个客户端已连接");
                    }
                } catch (Exception e) {
                    System.out.println("服务无法在" + port + "端口启动, 或服务异常停止");
                } finally {
                    close();
                }
            }
        }.start();
    }
}
